package a10_动态规划;

/**
 * <p>
 * a49_两个字符串的删除操作复习1
 * </p>
 *
 * @author flyduck
 * @since 2025/3/5
 */
public class a49_两个字符串的删除操作复习1 {
    //dp[i][j]：下标从0~i-1的chars1数组 和 下标从0~j-1的chars2数组 最少删除dp[i][j]次才能相等

    //递推公式
    //if(chars1[i-1] == chars2[j-1])
    //dp[i][j] = dp[i-1][j-1]
    //if(chars1[i-1] != chars2[j-1])
        //假设删除chars1[i-1]
        //dp[i][j] = dp[i-1][j] + 1
        //假设删除chars2[j-1]
        //dp[i][j] = dp[i][j-1] + 1
        //假设删除chars1[i-1]和chars2[j-1]
        //dp[i][j] = dp[i-1][j-1] + 2

    //初始化
    //dp[i][0] = i
    //dp[0][j] = j
    public int minDistance(String word1, String word2) {
        char[] chars1 = word1.toCharArray();
        char[] chars2 = word2.toCharArray();

        int[][] dp = new int[chars1.length+1][chars2.length+1];
        for (int i = 0; i <= chars1.length; i++) {
            dp[i][0] = i;
        }

        for (int j = 0; j <= chars2.length; j++) {
            dp[0][j] = j;
        }

        for (int i = 1; i <= chars1.length; i++) {
            for (int j = 1; j <= chars2.length; j++) {
                if(chars1[i-1] == chars2[j-1]){
                    dp[i][j] = dp[i-1][j-1];
                }else {
                    dp[i][j] = Math.min(Math.min(dp[i-1][j] + 1,dp[i][j-1] + 1), dp[i-1][j-1] + 2);
                }
            }
        }

        return dp[chars1.length][chars2.length];
    }
}
